package main

import (
	"./log"
	"./task"
	"./upyun"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

type Command struct {
	Cmd       string //cmd name [download,upload]
	UpyunPath string
	LocalPath string
	FileType  string // file type [file,folder,unknow]
}
type Input struct {
	BucketName string
	UserName   string
	PassWord   string
	EndPoint   string
	CmdList    []Command
}

var logger log.Logger

func main() {
	input_string, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		logger.Critical("ioutil.ReadAll fail!" + err.Error())
	}
	input_obj := &Input{}
	err = json.Unmarshal(input_string, input_obj)
	if err != nil {
		logger.Critical("json.Unmarshal fail!:" + err.Error())
	}
	upyun_obj := upyun.NewUpYun(input_obj.BucketName,
		input_obj.UserName,
		input_obj.PassWord)
	if input_obj.EndPoint!=""{
	    upyun_obj.SetApiDomain(input_obj.EndPoint)
	}
	tm := task.NewLimitThreadTaskManager(10)
	bulk_upyun := upyun.BulkUpyun{
		UpYun: upyun_obj,
		Tm:    tm,
	}
	for _, this_cmd := range input_obj.CmdList {
		switch this_cmd.Cmd {
		case "download":
			if this_cmd.FileType == "unknow" {
				this_cmd.FileType, err = bulk_upyun.GetFileType(this_cmd.UpyunPath)
				if err != nil {
					logger.LogError(err)
				}
			}
			if this_cmd.FileType == "folder" {
				bulk_upyun.DownloadDir(this_cmd.UpyunPath, this_cmd.LocalPath)
			} else if this_cmd.FileType == "file" {
				bulk_upyun.DownloadFile(this_cmd.UpyunPath, this_cmd.LocalPath)
			} else {
				logger.Error("unknow file type with download cmd:" + this_cmd.FileType)
			}
		case "upload":
			if this_cmd.FileType == "unknow" {
				fi, err := os.Stat(this_cmd.LocalPath)
				if err != nil {
					logger.LogError(err)
				}
				if fi.IsDir() {
					this_cmd.FileType = "folder"
				} else {
					this_cmd.FileType = "file"
				}
			}
			if this_cmd.FileType == "folder" {
				bulk_upyun.UploadDir(this_cmd.UpyunPath, this_cmd.LocalPath)
			} else if this_cmd.FileType == "file" {
				bulk_upyun.UploadFile(this_cmd.UpyunPath, this_cmd.LocalPath)
			} else {
				logger.Error("unknow file type with upload command:" + this_cmd.FileType)
			}
		case "delete":
			if this_cmd.FileType == "unknow" {
				this_cmd.FileType, err = bulk_upyun.GetFileType(this_cmd.UpyunPath)
				if err != nil {
					logger.LogError(err)
				}
			}
			if this_cmd.FileType == "folder" {
				bulk_upyun.DeleteDir(this_cmd.UpyunPath)
			} else if this_cmd.FileType == "file" {
				bulk_upyun.DeleteFile(this_cmd.UpyunPath)
			} else {
				logger.Error("unknow file type with download cmd:" + this_cmd.FileType)
			}
		default:
			logger.Error("unknow cmd:" + this_cmd.Cmd)
		}
	}
	tm.Wait()
	fmt.Println("finish")
}
